'use strict';
const { Blog, db, Op } = require('../db');
const baseOptions = {
    attributes: ['id', 'title', 'digest', 'content', 'classification', 'author', 'publish_time'],
    order: ['id']
}

module.exports = {
    'get /blog': async ctx => {
        let keyword = ctx.request.query.keyword;
        let optins = {...baseOptions};

        if (keyword) {
            optins.where = {
                [Op.or]: [
                    {id: isNaN(keyword) ? 0 : keyword},
                    {title: keyword},
                    {digest: keyword},
                    {content: keyword},
                    {classification: keyword},
                    {author: keyword},
                    {publish_time: keyword},
                ]
            }

        }

        let data = await Blog.findAll(optins);
        ctx.body = data;
    },
    'get /blog/:id': async ctx => {
        let id = ctx.request.params.id;
        let data = await Blog.findByPk(id, baseOptions);
        ctx.body = data;
    },
    'post /blog': async ctx => {
        let data = ctx.request.body;
        let id = await Blog.create(data);
        ctx.body = id;
    },
    'put /blog/:id': async ctx => {
        let id = ctx.request.params.id;
        let data = ctx.request.body;

        await Blog.update(data, {
            where: {
                id
            }
        })

        ctx.body = id;
    },
    'del /blog/:id': async ctx => {
        let id = ctx.request.params.id;
        await Blog.destroy({where: {
            id
        }});
        ctx.body = id;
    },
}